<?php

class AuthController extends Zend_Controller_Action {

	public function init() {
		Zend_Layout::getMvcInstance()->setLayout('auth');
	}
	
	public function loginAction() {
		$form = new Default_Form_Login();
		$form->setMethod('post');
		$form->setAction($this->view->url(array(), 'default_auth_login'));
		
		$modelName = 'Users_Model_Users';
		
		if($this->_request->isPost() && $form->isValid($this->_request->getPost())) {
			$username = $form->getValue('login');
			$password = $form->getValue('password');
			$remember = $form->getValue('remember');
			
			
			$auth = Zend_Auth::getInstance();
			
			$authAdapter = new ZendX_Doctrine_Auth_Adapter(
								Doctrine_Core::getConnectionByTableName($modelName),
								($modelName . ' u'),
								'u.email = ? OR u.username',
								'u.password',
								'MD5(?) AND u.delete = "no"');
			$authAdapter->setIdentity(array($username, $username))
                        ->setCredential($password);
			
			
			$result = $auth->authenticate($authAdapter);
			
			if ($result->isValid()) {
				$storage = new Zend_Auth_Storage_Session();
				$storage->write($authAdapter->getResultRowObject());
				//если нажата кнопка запомнить
				if(!intval($remember) > 0) {
					Zend_Session::rememberMe(60*60*24*14);
				}
				return $this->_redirect($this->view->url(array(), 'default_index_index'));
			} else {
				$this->_helper->getHelper('FlashMessenger')
					->addMessage($this->view->translate('Error with authenticate!'));
				return $this->_redirect($this->view->url(array(), 'default_auth_login'));
			}
		}
		
		$this->view->form = $form;
	}
	
	public function denyAction() {
		$this->getResponse()
            ->setHttpResponseCode(403);
	}
}